/// <reference path="../../../../../global.d.ts" />

/** 生成diy表单 */
function writeBackDIYForm (data) {
  /* 小类id */
  let id = data.m_group
  /* 小类内容 */
  let value = data.m_value
  /**
   * DIYform 的id
   */
  let formID = data.m_group

  function genDIYNumberLine (Obj, uniID) {
    return `
    <div class="input_wrap number_input" id='hidden_from_backend${uniID}'
    inori-md_id='${Obj.m_3id}'
    inori-input_type='${Obj.input_type}'
    inori-m_group='${Obj.group}_${uniID.replace(/\d{1,}_\d{1,}_/, '')}'
    inori-bq_id='${Obj.group}'
    >
      <div class='form_line_title'>${Obj.title}:</div>
      <!-- 固定隐藏input，用于后端分辨该行表单类型 -->
      <input type='hidden' name='type' value='1'>
      <div class="alt_data" style='display:none;'>
        <select
          form = 'not_submit' name="[alt_data]"
          aria-multiple = 'false'
        >
          <option value="大于">大于</option>
          <option value="大于等于">大于等于</option>
          <option value="小于">小于</option>
          <option value="小于等于">小于等于</option>
          <option value="等于">等于</option>
        </select>
      </div>
      <div class="main_data">
        <input type="num" form='not_submit' name="[main_data]" placeholder="请填写答案" value=''>
      </div>
    </div>
    <script id='tempmlScript${uniID}'>
      $('#hidden_from_backend${uniID} .alt_data select').select2({
        placeholder: '请选择取值方向',
        tags: false,
        multiple: false,
        minimumResultsForSearch: Infinity,
        width: 'element'
      }).val(null).trigger('change')
      setTimeout(()=>{$('#tempmlScript${uniID}').remove()}, 0)
    </script>
    `.trim()
  }
  function genDIYSLine (Obj, uniID) {
    let options = ``
    let templ = `
      <div class="input_wrap single_select" id='hidden_from_backend${uniID}'
      inori-md_id='${Obj.m_3id}'
      inori-input_type='${Obj.input_type}'
      inori-m_group='${Obj.group}_${uniID.replace(/\d{1,}_\d{1,}_/, '')}'
      inori-bq_id='${Obj.group}'
      >
        <input type='hidden' name='type' value='2'>
        <div class='form_line_title'>${Obj.title}:</div>
        <div class="main_data">
            <select
              form = 'not_submit' name="[main_data]"
            >
              <option inori-id='here-inori'></option>
            </select>
        </div>
      </div>
      <script id='tempmlScript${uniID}'>
        $('#hidden_from_backend${uniID} .alt_data select').select2({
          placeholder: '无需选择',
          tags: false,
          multiple: false,
          width: 'element'
        })
        $('#hidden_from_backend${uniID} .main_data select').select2({
          placeholder: '请选择具体选项',
          tags: false,
          multiple: false,
          minimumResultsForSearch: Infinity,
          width: 'element'
        }).val(null).trigger('change')
        setTimeout(()=>{$('#tempmlScript${uniID}').remove()}, 0)
      </script>
    `.trim()
    $.each(Obj.main_data, function (index, opn) {
      /* 其实 `text === value` */
      options += `<option value='${opn.value}' inori-data='${opn.key}'>${opn.text}</option>`
    })
    return templ.replace(`<option inori-id='here-inori'></option>`, options)
  }
  function genDIYMLine (Obj, uniID) {
    let options = '<optgroup label="">'
    let templ = `
      <div class="input_wrap multiple_select" id='hidden_from_backend${uniID}'
      inori-md_id='${Obj.m_3id}'
      inori-input_type='${Obj.input_type}'
      inori-m_group='${Obj.group}_${uniID.replace(/\d{1,}_\d{1,}_/, '')}'
      inori-bq_id='${Obj.group}'
      >
        <!-- 固定隐藏input，用于后端分辨该行表单类型 -->
        <input type='hidden' name='type' value='3'>
        <div class='form_line_title'>${Obj.title}:</div>
        <div class="alt_data" style='display:none;'>
          <select
            form = 'not_submit' name="[alt_data]"
          >
            <optgroup label="">
                <option value="同时符合">同时符合</option>
                <option value="任意符合">任意符合</option>
              </optgroup>
          </select>
        </div>
        <div class="main_data">
            <select
              form = 'not_submit' name="[main_data][]"
            >
            <option inori-id='here-inori'></option>
            </select>
        </div>
      </div>
      <script id='tempmlScript${uniID}'>
        $('#hidden_from_backend${uniID} .alt_data select').select2({
          placeholder: '请选择具体选项（必填）',
          tags: false,
          multiple: false,
          minimumResultsForSearch: Infinity,
          width: 'element'
        })
        $('#hidden_from_backend${uniID} .main_data select').select2({
          placeholder: '请选择具体选项（必填）',
          // tags: true,
          multiple: true,
          tokenSeparators: [',', ' '],
          width: 'element',
          minimumResultsForSearch: Infinity,
          closeOnSelect: false
        }).val(null).change()
        setTimeout(()=>{$('#tempmlScript${uniID}').remove()}, 0)
      </script>
      `.trim()
    $.each(Obj.main_data, function (index, opn) {
      /* 其实 `text === value` */
      options += `<option value='${opn.value}' inori-data='${opn.key}'>${opn.text}</option>`
    })
    options += '</optgroup>'
    return templ.replace(`<option inori-id='here-inori'></option>`, options)
  }
  function genDIYForm (tagMessage, formID, formData) {
    let templ = ``
    const switchObj = {
      1: genDIYNumberLine,
      2: genDIYSLine,
      3: genDIYMLine
    }
    $.each(formData, function (index, Obj) {
      templ += switchObj[Obj.input_type](Obj, `${formID}_${tagMessage.id}_${index}`)
    })
    // 添加表格之前去除提示文字
    $('.placeholder').remove()
    $('.DIYForm').append(templ)
    console.log('done')
  }

  genDIYForm({id: id, value: value}, formID, data.formData)
}

/**
 * 生成后端需要的数据格式表单
 */
function genNewForm(postBtnID) {
  let formName = `tempForm`
  const formURL = $('#hidden_form_1').attr('action')
  let templ = `<form autocomplete="off" action="${formURL}" id='${formName}' method="post"></form>`
  $(`#${formName}`).remove()
  $('body').append(templ)
  const formWrap = $('.input_wrap')
  const xiaoleiID = $(`body`).attr('inori-xiaolei-id')
  formWrap.each((index, item) => {
    // * 8=>array(
    // *      0 =>array(
    // *         0=>'xiaoleiID',
    // *         1=>array(
    // *           'fromdata' =>
    // *               array(
    // *                  0=>array(
    // *                    'md_id' =>m_3id,
    // *                    'input_type' =>1,
    // *                    'm_group' =>'155_0',
    // *                    'bq_id' =>'155',
    // *                    'maindata' =>123,
    // *                    'altdata' =>'小于等于',
    // *                  )
    // *               )
    // *           )
    // *       )
    // *    )
    let templItem = ``
    const mdID = $(item).attr('inori-md_id')
    const inputType = $(item).attr('inori-input_type')
    const mGroup = $(item).attr('inori-m_group')
    const bqID = $(item).attr('inori-bq_id')
    let maindata = []
    let altdata
    if (String(inputType) === '1') {
      maindata = [`${$(item).find('.main_data input').val()}`]
    } else {
      // maindata = Array($(item).find('.main_data select').val()).join(',')
      maindata = $(item).find(`[name*='[main_data]'] option`).map(function () {
        if ( String($(item).find(`[name*='[main_data]']`).val()).indexOf($(this).attr('value')) > -1 ) {
          /** 自增数字 */
          let key = $(this).attr('inori-data')
          return key
        }
      })
    }
    // 环回引用
    // maindata = JSON.parse(JSON.stringify(maindata))
    let pureMaindata = []
    $.each(maindata, (index, item) => {
      pureMaindata.push(item)
    })
    maindata = pureMaindata
    if (String(inputType) !== '2') {
      altdata = $(item).find('.alt_data select').val()
    } else {
      altdata = ''
    }
    templItem += `<input type='hidden' name='8[0][1][formdata][${index}][md_id]' value='${mdID}'>`
    templItem += `<input type='hidden' name='8[0][1][formdata][${index}][input_type]' value='${inputType}'>`
    templItem += `<input type='hidden' name='8[0][1][formdata][${index}][m_group]' value='${mGroup}'>`
    templItem += `<input type='hidden' name='8[0][1][formdata][${index}][bq_id]' value='${bqID}'>`
    templItem += `<input type='hidden' name='8[0][1][formdata][${index}][maindata]' value='${maindata}'>`
    templItem += `<input type='hidden' name='8[0][1][formdata][${index}][altdata]' value='${altdata}'>`
    /* 上一个页面提交的结构，这里是因为想少做一次生成，后端要求的数据结构跟表单的直接结构有点区别 */
    let PreViewForm = sessionStorage.getItem('newPingu')
    try {
      PreViewForm = JSON.parse(PreViewForm)
    } catch (e) {
      console.log(e)
      PreViewForm = null
    }
    if (PreViewForm !== null) {
      for(let item of PreViewForm) {
        templItem += `<input type='hidden' name='${item.name}' value='${item.value}'>`
      }
    }
    $(`#${formName}`).append(templItem)
  })
  $(`#${formName}`).append(`<input type='hidden' name='8[0][0]' value='${xiaoleiID}'>`)
  return formName
}

/* 页面还原 */
$(document).ready(() => {
  let sessionValue = sessionStorage.getItem('rawFormData_2')
  // let sessionValue = `[{"name":"qudao_type_only_one","value":"银行"},{"name":"chanpin_type_only_one","value":"155"},{"name":"daikuan_local","value":"北京 北京市 东城区"}]`
  const getFormURL = String($('#get_new_free_form').val())
  let xiaoleiID = false
  sessionValue = JSON.parse(sessionValue)
  for (let item of sessionValue) {
    if (item.name === 'chanpin_type_only_one') {
      xiaoleiID = item.value
    }
  }
  if (xiaoleiID === false) {
    $.toptip('找不到所需数据，请关闭页面重试。如多次发生请联系管理员', 'error')
    throw new Error('找不到所需数据，请关闭页面重试。如多次发生请联系管理员')
  }
  $('body').attr('inori-xiaolei-id', String(xiaoleiID))
  $.ajax(getFormURL, {
    method: 'POST',
    data: {m_group: xiaoleiID}
  }).done((data) => {
    if (data.formData && data.formData.length > 0) {
      writeBackDIYForm(data)
    } else {
      $('.DIYForm').text('服务器没有对应详细搜索指引，请返回上一步选择其他标签')
    }
  }).fail((err) => {
    console.log(err)
    $('.DIYForm').text('数据请求失败，请检查网络')
  })
})
